package Usermanagement

import (
	"database/sql"
	"fmt"
	"log"
)

func index_user() int {
	var userID int
	fmt.Println("请输入用户Id")
	fmt.Scan(&userID)
	return userID
}

func SelectUser(db *sql.DB, userID int) (*Mainfase, error) {
	var m Mainfase
	query := `SELECT id,name, gender, age, email FROM Manager_users WHERE id = $1`
	row := db.QueryRow(query, userID)
	err := row.Scan(&m.Id, &m.Name, &m.Gender, &m.Age, &m.Email)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, fmt.Errorf("no user found with ID %d", userID)
		}
		return nil, err
	}
	return &m, nil
}

func getAllUsers() ([]Mainfase, error) {
	db, err := ConnectDB()
	query := `SELECT id,name, gender, age, email FROM Manager_users`
	rows, err := db.Query(query)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var users []Mainfase
	for rows.Next() {
		var m Mainfase
		err := rows.Scan(&m.Id, &m.Name, &m.Gender, &m.Age, &m.Email)
		if err != nil {
			return nil, err
		}
		users = append(users, m)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return users, nil
}
func GetAlluser() {
	var indeId int
	users, err := getAllUsers()
	if err != nil {
		log.Fatal(err)
	}
	for _, u := range users {
		indeId += 1
		fmt.Printf("用户ID为%d,用户姓名: %s,用户性别: %s,用户年龄: %d,用户邮箱: %s\n", u.Id, u.Name, u.Gender, u.Age, u.Email)
	}
}

func Select_user() {
	index_user_data := index_user()
	var select_number_bool string
	db, err := ConnectDB()
	if err != nil {
		log.Fatal("数据库连接失败:", err)
	}
	defer db.Close()
	for {
		if index_user_data == 0 {
			fmt.Println("请输入你要查询的用户序号")
			fmt.Scan(&index_user_data)
		}
		user, err := SelectUser(db, index_user_data)
		if err != nil {
			fmt.Println(err)
			index_user_data = 0
			continue
		}
		fmt.Printf("序号为%d  姓名:%s  性别:%s  年龄%d  邮箱:%s\n",
			index_user_data,
			user.Name,
			user.Gender,
			user.Age,
			user.Email)
		fmt.Print("是否返回上一层[y/n]：")
		fmt.Scan(&select_number_bool)
		if select_number_bool == "y" {
			break
		} else if select_number_bool == "n" {
			index_user_data = 0
			continue
		} else {
			fmt.Println("请重新输入你的选择{y/n}")
		}
	}
}
